import router from './router';
import Nprogress from 'nprogress';
import 'nprogress/nprogress.css';
import { useUserStore } from './store/user';

Nprogress.configure({
	showSpinner: false,
});

router.beforeEach((to, _from, next) => {
	// 解决 hash 模式不能用微信登录
	const w = location.href.indexOf('?');
	const j = location.href.indexOf('#');
	if (w !== -1 && j > w) {
		const query = location.href.slice(w + 1, j);

		window.location.href = window.location.origin + window.location.pathname + '#/wxlogin?' + query;

		return;
	}

	Nprogress.start();

	const userStoer = useUserStore();

	if (userStoer.userInfo.token) {
		next();
	} else {
		if (to.meta.requiredLogin) {
			next({
				path: '/home',
				query: {
					redirect: to.fullPath,
				},
			});

			userStoer.visible = true;
		} else {
			next();
		}
	}
});

router.afterEach((to) => {
	Nprogress.done();

	document.title = '尚医通 - ' + to.meta.title;
});
